﻿using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Orm.Metadata.DataEntity;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Web;

namespace WSDZ.KM.ZH.XiaoManIntegrating40
{
    public static class ExtendManeger
    {
        public static bool EqualsV1(this string A, string B)
        {
            return A.ToStringV1().Equals(B.ToStringV1(), StringComparison.OrdinalIgnoreCase);
        }
        public static bool EqualsV2(this string A, string B)
        {
            return A.ToStringV1().Replace(" ","").Equals(B.ToStringV1().Replace(" ", ""), StringComparison.OrdinalIgnoreCase);
        }
        /// <summary>
        /// 判断值是否为空，并转为string
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToStringV1(this object obj)
        {
            return obj is System.DBNull || obj is null ? "" : obj.ToString().Trim();
        }
        /// <summary>
        /// 判断值是否为空，并转为string，并把‘替换成空字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToStringV2(this object obj)
        {
            return obj is System.DBNull || obj is null ? "" : obj.ToString().Trim().Replace("'", "");
        }
        /// <summary>
        /// 判断值是否为空，并转为string，并把‘替换成空字符串,并转成大写
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToStringV3(this object obj)
        {
            return obj is System.DBNull || obj is null ? "" : obj.ToString().Replace("'", "").ToUpper();
        }
        public static bool ToBoolean(this object obj)
        {
            bool result = false;
            if (!(obj is null) && !(obj is DBNull))
            {
                try
                {
                    string objStr = obj.ToStringV1();
                    if (objStr.EqualsV1("true")|| objStr.EqualsV1("1"))
                        result = true;
                    else if (objStr.EqualsV1("false") || objStr.EqualsV1("0"))
                        result = false;
                    else
                    {
                        result = Convert.ToBoolean(obj);
                    }
                }
                catch (Exception)
                {
                    return false;
                }
            }
            return result;
        }
        public static bool ContainsNoCase(this string source, string toCheck, StringComparison comp = StringComparison.OrdinalIgnoreCase)
        {
            return source.IndexOf(toCheck, comp) >= 0;
        }
        /// <summary>
        /// object 转 bool
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool ToBooleanV1(this object obj)
        {
            bool result = false;
            if (!(obj is null) && !(obj is DBNull))
            {
                try
                {
                    result = Convert.ToBoolean(obj);
                }
                catch (Exception)
                {
                }
            }
            return result;
        }
        /// <summary>
        /// object转int
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static int ToInt32V1(this object obj)
        {
            int result = 0;
            if (!(obj is null) && !(obj is DBNull))
            {
                try
                {
                    result = Convert.ToInt32(obj);
                }
                catch (Exception)
                {
                }
            }
            return result;
        }
        public static long ToInt64(this object obj)
        {
            long result = 0;
            if (!(obj is null) && !(obj is DBNull))
            {
                try
                {
                    result = Convert.ToInt64(obj);
                }
                catch (Exception)
                {
                }
            }
            return result;
        }
        /// <summary>
        /// obj转bool
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool ToBoolenV1(this object obj)
        {
            bool ires = false;
            if (!(obj is null) && !(obj is System.DBNull))
            {
                try
                {
                    ires = Convert.ToBoolean(obj);
                }
                catch (Exception)
                {
                }

            }
            return ires;
        }
        /// <summary>
        /// obj转decimal
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static decimal ToDecimalV1(this object obj)
        {
            decimal dec = 0;
            try
            {
                if (!(obj is System.DBNull) && !(obj is null))
                {
                    dec = Convert.ToDecimal(obj);
                }
            }
            catch (Exception)
            {
                dec = 0;
            }
            return dec;

        }
        /// <summary>
        /// obj转decimal
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static double ToDoule(this object obj)
        {
            double dec = 0;
            try
            {
                if (!(obj is System.DBNull) && !(obj is null))
                {
                    dec = Convert.ToDouble(obj);
                }
            }
            catch (Exception)
            {
                dec = 0;
            }
            return dec;

        }

        public static decimal ToDigits(this decimal obj,int digit=0)
        {
            if (digit==0)
                return obj.ToInt32V1();
            return Math.Round(obj,digit);
        }
        public static string ToDigitsV1(this object obj, string digit = "N0")
        {
            return obj.ToDecimalV1().ToString(digit);
        }

        /// <summary>
        /// 判断值是否为空，并转小写
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToStrLower(this object obj)
        {
            return obj is System.DBNull || obj is null ? "" : obj.ToString().ToLower();
        }
        /// <summary>
        /// obj转DateTime
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static DateTime ToDateTime(this object obj)
        {
            DateTime dec = Convert.ToDateTime("1900-01-01");
            try
            {
                if (!(obj is System.DBNull) && !(obj is null))
                {
                    dec = Convert.ToDateTime(obj);
                }
            }
            catch (Exception ex)
            {
            }
            return dec;

        }
        /// <summary>
        /// 时间字符串为空，则返回时间默认值 字符串
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static string ToDefaultTimeStr(this string time)
        {
            string res = "1900-01-01 00:00:00";
            try
            {
                DateTime d = Convert.ToDateTime(time);
                res = d.ToString("yyyy-MM-dd HH:mm:ss");
            }
            catch (Exception)
            {
                return "1900-01-01 00:00:00";
            }
            return res;
        }
        /// <summary>
        /// 时间字符串为空，则返回空
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static string ToDefaultTimeStrV1(this string time)
        {
            string res = "";
            try
            {
                DateTime d = Convert.ToDateTime(time);
                res = d.ToString("yyyy-MM-dd HH:mm:ss");
            }
            catch (Exception)
            {
            }
            return res;
        }
        public static bool IsNullOrEmptyOrWhiteSpace(this string str)
        {
            return string.IsNullOrEmpty(str) || string.IsNullOrWhiteSpace(str);
        }

        public static DataSet XMLToDataSet(this string xml, bool AddHeader = true)
        {
            DataSet ds = new DataSet();
            string xmlHeader = @"<?xml version=""1.0"" encoding=""gb2312""?>";
            if (AddHeader)
            {
                xml = xmlHeader + xml.Replace("&", "");
            }
            using (StringReader xmlSR = new StringReader(xml))
            {
                ds.ReadXml(xmlSR, XmlReadMode.InferSchema);
                xmlSR.Close();
            }
            return ds;
        }

        /// <summary>
        /// DataTable转成List
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <param name="isNullToEmpty">是否将null转为空格</param>
        /// <returns></returns>
        public static List<T> ToDataList<T>(this DataTable dt,bool isNullToEmpty=true)
        {
            if (dt == null || dt.Rows.Count < 1)
            {
                return new List<T>();
            }
            var list = new List<T>();
            var plist = new List<PropertyInfo>(typeof(T).GetProperties());
            foreach (DataRow item in dt.Rows)
            {
                try
                {
                    T s = Activator.CreateInstance<T>();
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        PropertyInfo info = plist.Find(p => p.Name.EqualsV1(dt.Columns[i].ColumnName));
                        if (info != null)
                        {
                            object v = null;
                            if (!Convert.IsDBNull(item[i]))
                            {
                                if (info.PropertyType.ToString().Contains("System.Nullable"))
                                {
                                    v = Convert.ChangeType(item[i], Nullable.GetUnderlyingType(info.PropertyType));
                                }
                                else
                                {
                                    v = Convert.ChangeType(item[i], info.PropertyType);
                                }
                                info.SetValue(s, v, null);
                            }
                            else
                            {
                                if (info.PropertyType.ToString().Contains("System.String")&& isNullToEmpty)
                                {
                                    v = "";
                                    info.SetValue(s, v, null);
                                }
                            }
                        }
                    }
                    list.Add(s);
                }
                catch (Exception ex)
                {

                    throw;
                }

            }
            return list;
        }

        /// <summary>
        /// DynamicObjectCollection转成List
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <param name="isNullToEmpty">是否将null转为空格</param>
        /// <returns></returns>
        public static List<T> DynamicObjectCollectionToDataList<T>(this DynamicObjectCollection dyList, bool isNullToEmpty = true)
        {
            if (dyList == null || dyList.Count < 1)
                return new List<T>();
            var list = new List<T>();
            var plist = new List<PropertyInfo>(typeof(T).GetProperties());
            DynamicObjectType objType = dyList.DynamicCollectionItemPropertyType;
            DynamicPropertyCollection types = objType.Properties;
            foreach (DynamicObject obj in dyList)
            {
                try
                {
                    T s = Activator.CreateInstance<T>();
                    for (int i = 0; i < types.Count; i++)
                    {
                        PropertyInfo info = plist.Find(p => p.Name.EqualsV1(types[i].Name));
                        if (info != null)
                        {
                            object v = null;
                            if (!Convert.IsDBNull(obj[i]))
                            {
                                if (info.PropertyType.ToString().Contains("System.Nullable"))
                                {
                                    v = Convert.ChangeType(obj[i], Nullable.GetUnderlyingType(info.PropertyType));
                                }
                                else
                                {
                                    v = Convert.ChangeType(obj[i], info.PropertyType);
                                    if (v is null&& info.PropertyType.ToString().Contains("System.String") && isNullToEmpty)
                                        v = "";
                                }
                                info.SetValue(s, v, null);
                            }
                            else
                            {
                                if (info.PropertyType.ToString().Contains("System.String") && isNullToEmpty)
                                {
                                    v = "";
                                    info.SetValue(s, v, null);
                                }
                            }
                        }
                    }
                    list.Add(s);
                }
                catch (Exception ex)
                {

                    throw;
                }

            }
            return list;
        }

        /// <summary>
        /// (秒)时间戳转时间
        /// </summary>
        /// <param name="lon"></param>
        /// <returns></returns>
        public static DateTime TimestampToDateTime(this long lon)
        {
            DateTime d1 = default(DateTime);
            try
            {
                System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));//当地时区
                d1 = startTime.AddSeconds(lon);
            }
            catch (Exception)
            {
            }
            return d1;
        }
        /// <summary>
        /// 时间转(秒)时间戳
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static long DateTimeToTimestamp(this DateTime time)
        {
            long lon = default(long);
            try
            {
                System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));//当地时区
                TimeSpan ts = time - startTime;
                lon = Convert.ToInt64(ts.TotalSeconds);
            }
            catch (Exception)
            {
            }
            return lon;
        }
        public static long GetTimeStampV1(this DateTime date,bool ismilliseconds = false)
        {
            var time = new DateTimeOffset(date);
            var timestamp = 0L;
            if (ismilliseconds)
            {
                timestamp = time.ToUnixTimeMilliseconds();
            }
            else
                timestamp = time.ToUnixTimeSeconds();

            return timestamp;
        }
        public static bool ContainsV1(this List<string> list, string b)
        {
            if (list == null || list.Count < 1 || b.IsNullOrEmptyOrWhiteSpace())
                return false;
            return list.Contains(b,StringComparer.OrdinalIgnoreCase);
        }
        public static HttpResponseMessage ToReturnJson(this string content)
        {
            try
            {
                return new HttpResponseMessage { Content = new StringContent(content, Encoding.GetEncoding("UTF-8"), "application/json") };
            }
            catch (Exception ex)
            {
                return new HttpResponseMessage { Content = new StringContent(ex.Message, Encoding.GetEncoding("UTF-8"), "application/json") };
            }

        }


    }
}